import { Component, OnInit } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { OtcShopService } from '@core/routes-services/otc-shop.service';
import { OTC_SHOP_CUS_ROLE } from '../../../constant/dictionary';

@Component({
  selector: 'app-otc-cus-shop-role',
  templateUrl: './otc-cus-shop-role.component.html',
})
export class OtcCusShopRoleComponent implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = true;

  otcShopCusRole: any [] = OTC_SHOP_CUS_ROLE;

  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private otcShopService: OtcShopService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.initValidateForm();
    this.otcShopCusRole = this.otcShopCusRole.filter(e => e.key != 3);
    setTimeout(() => (this.isLoading = false), 500);
  }


  initValidateForm() {
    this.validateForm = this.fb.group({
      name: [this.entity.name, []],
      title: [this.entity.title, []],
      role: [this.entity.role, [Validators.required]],
    });
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      // console.log(this.validateForm.value);
      this.otcShopService.updateCusShopRole(this.entity.id, this.validateForm.value.role).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.modal.close(true);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });

    }
  }

  close() {
    this.modal.destroy();
  }
}
